
<template>
  <div class="app-container action-account-container">
    <div class="back-content flex-normal">
      <span class="back-icon el-icon-back" @click="$router.go(-1)"></span>
      <span class="back-label">{{ other.key == 'reset' ? '重新开户' : '账户开户'}}</span>
    </div>
    <div class="action-account-main flex-between">
      <div class="app-dialog" v-if="boo.flash">
        <el-form
          class="form-content"
          ref="account-form" label-position="left"
          :model="currentItem"
          label-width="140px" :rules="rules">
          <div class="form-title">账户基本信息</div>
          <el-form-item class="form-content-item"
            label="账户手机号：" prop="accountPhone">
            <div class="form-val flex-normal">
              <el-input v-model="currentItem['accountPhone']" placeholder="请输入手机号"></el-input>
            </div>
          </el-form-item>
          <el-form-item class="form-content-item"
              label="验证码：" prop="code">
              <div class="form-val flex-normal">
                <el-input v-model="currentItem['code']" placeholder="请输入验证码"></el-input>
                <el-button class="code-btn-unit" type="text" @click="sendCode" :loading="timerObj.loading">{{timerObj.tips}}</el-button>
              </div>
          </el-form-item>
          <div class="form-title">账户资料</div>
          <el-form-item class="form-content-item"
              label="账户类型：" prop="accountType">
            <div class="form-val no-border flex-normal">
              <el-radio-group v-model="currentItem['accountType']" @change="radioChange">
                <el-radio :label="1">个人</el-radio>
                <el-radio :label="2">企业</el-radio>
              </el-radio-group>
            </div>
          </el-form-item>
          <el-form-item class="form-content-item"
            label="证件类型：" prop="certificateType">
            <div class="form-val flex-normal">
              <el-input readonly v-model="currentItem['certificateType']" :placeholder="currentItem.radio == 1 ? '身份证' : '企业营业执照'"></el-input>
            </div>
          </el-form-item>
          <el-form-item class="form-content-item" prop="certificatePhotoFront"
              label="证件照片：" v-if="currentItem['accountType'] == 1">
            <div class="form-val no-border flex-normal">
              <div class="sfz-item flex-column">
                <upload-image v-model="currentItem['certificatePhotoFront']" icon-name="sfz-zm" @change="uploadImage">
                </upload-image>
                <span class="warning-txt">持卡人身份证（正面）</span>
              </div>
              <div class="sfz-item flex-column">
                <upload-image v-model="currentItem['certificatePhotoBack']" icon-name="sfz-fm">
                </upload-image>
                <span class="warning-txt">持卡人身份证（背面）</span>
              </div>
            </div>
          </el-form-item>
          
          <el-form-item class="form-content-item"
              label="营业执照：" prop="businessLicense" v-if="currentItem['accountType'] == 2">
            <div class="form-val no-border flex-normal">
              <div class="yyzz-item flex-column">
                <upload-image v-model="currentItem['businessLicense']" icon-name="yyzz">
                </upload-image>
                <span class="warning-txt">营业执照复印件</span>
              </div>
            </div>
          </el-form-item>
          <el-form-item class="form-content-item"
              label="法人身份证：" prop="certificatePhotoFront" v-if="currentItem['accountType'] == 2">
            <div class="form-val no-border flex-normal">
              <div class="sfz-item flex-column">
                <upload-image v-model="currentItem['certificatePhotoFront']" icon-name="sfz-fm">
                </upload-image>
                <span class="warning-txt">持卡人身份证（正面）</span>
              </div>
              <div class="sfz-item flex-column">
                <upload-image v-model="currentItem['certificatePhotoBack']" icon-name="sfz-fm">
                </upload-image>
                <span class="warning-txt">持卡人身份证（背面）</span>
              </div>
            </div>
          </el-form-item>
          <el-form-item class="form-content-item"
              label="账户持有人：" prop="accountUserName">
              <div class="form-val flex-normal">
                <el-input v-model="currentItem['accountUserName']" placeholder="请输入账户持有人姓名"></el-input>
              </div>
          </el-form-item>
          <el-form-item class="form-content-item" v-if="currentItem['accountType'] == 1"
              label="身份证号：" prop="certificateNumber">
              <div class="form-val flex-normal">
                <el-input v-model="currentItem['certificateNumber']" 
                placeholder="请输入账户持有人身份证号" @change="validateNum" @input="validateNum"></el-input>
              </div>
          </el-form-item>
          <el-form-item class="form-content-item" v-if="currentItem['accountType'] == 2"
              label="企业邮箱：" prop="regEmail">
              <div class="form-val flex-normal">
                <el-input v-model="currentItem['regEmail']" placeholder="请输入企业邮箱"></el-input>
              </div>
          </el-form-item>
          <el-form-item class="form-content-item" v-if="currentItem['accountType'] == 2"
              label="统一信用编码：" prop="certificateNumber">
              <div class="form-val flex-normal">
                <el-input v-model="currentItem['certificateNumber']" 
                placeholder="请输入统一信用编码" @input="validateNum"></el-input>
              </div>
          </el-form-item>
        </el-form>
        <div class="btn-container flex-normal">
          <div class="btn-item reset flex-center">
            <el-button type="text" class="btn-txt" @click="reset">重置信息</el-button>
          </div>
          <div class="btn-item submit flex-center">
            <!-- <el-button class="btn-txt" type="primary" @click="jumpPage('actionCardPerson')">提交开户申请</el-button> -->
            <el-button class="btn-txt" type="primary" @click="submit('account')" :loading="boo.isSubmit">提交开户申请</el-button>
          </div>
        </div>
      </div>
      <div class="warning-content flex-column" v-if="currentItem.radio == 2">
        <span class="warning-label">开户说明：</span>
        <div class="list">
          <div class="item flex-normal" v-for="(desc, index) in warningList" :key="index">
            <span class="item-desc">{{ index + 1 }}、</span>
            <span class="item-desc" v-html="desc"></span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getOrc
} from "@/api/common/index";
import {
  openFinance, getFinanceIndex
} from "@/api/financeManage/shop-finance";

import { getLpayCode } from "@/api/financeManage/lpay.js";
import { isPhoneNum, trimAllStr } from "@/utils/tools.js";
export default {
  components: {
    'upload-image': () => import('@/views/components/uploadImage/index')
  },
  data() {
    const vm = this
    const validateSFZ = (rule, value, callback) => {
      let {certificatePhotoFront = '', certificatePhotoBack = ''} = vm.currentItem
      if(certificatePhotoFront == '') return callback(new Error('请上传身份证正面'));
      if(certificatePhotoBack == '') return callback(new Error('请上传身份证反面'));
      callback();
    }
    const validateTel = (rule, value, callback) => {
      if(!isPhoneNum(value)) return callback(new Error('请输入正确格式的手机号'));
      callback();
    }
    return {
      other: {
        key: ''
      },
      boo: {
        isSubmit: false,
        flash: true,
        loading: false
      },
      currentItem: {},
      warningList: [
        '如需充值，请使用手机银行或者网银，打款至存管账户',
        '存管账户转账仅限于工作日工作时间请安排好打款时间；',
        '转账充值操作必须使用与存管账户的同名账户，不支持非同名账户转账；',
        '服务过程中，如果有任何疑问，可致电客服：<br />400-810-0049反馈',
      ],
      rules: {
        accountPhone: [
          { required: true, message: '手机号不能为空', trigger: 'input' },
          { required: true, validator: validateTel, trigger: 'input' }
        ],
        code: [
          { required: true, message: '验证码不能为空', trigger: 'input' }
        ],
        accountType: [
          { required: true, message: '账户类型不能为空', trigger: 'change' }
        ],
        certificateType: [
          { required: true, message: '证件类型不能为空', trigger: 'input' }
        ],
        certificatePhotoFront: [
          { required: true, validator: validateSFZ, trigger: 'change'}
        ],
        businessLicense: [
          { required: true, message: '营业执照不能为空', trigger: 'change' }
        ],
        accountUserName: [
          { required: true, message: '账户持有人不能为空', trigger: 'input' }
        ],
        certificateNumber: [
          { required: true, message: '证件号码不能为空', trigger: 'input' }
        ],
        regEmail: [
          { required: true, message: '请输入正确的邮箱地址', trigger: 'input', type: 'email' }
        ]
      },
      timerObj: {
        timer: null,
        seconds: 60,
        loading: false,
        tips: '获取验证码'
      }
    };
  },
  mounted(){
    let _self = this
    let {key} = this.$route.query
    this.other.key = key
    _self.queryFinanceIndex()
    if(_self.timerObj.timer){
      clearInterval(_self.timerObj.timer)
      _self.timerObj.timer = null
    }
  },
  methods: {
    validateNum(){
      let _self = this
      let num = _self.currentItem.certificateNumber
      let str = num.replace(/\s/g, '').replace(/(.{4})/g, '$1 ')
      _self.$set(_self.currentItem, 'certificateNumber', str)
    },
    uploadImage(url){
      let _self = this
      getOrc({url}).then(res => {
        let { name, idNumber } = res.data
        _self.$set(_self.currentItem, 'accountUserName', name)
        _self.$set(_self.currentItem, 'certificateNumber', idNumber)
      })
    },
    queryFinanceIndex(){
      let _self = this
      _self.boo.loading = true
      getFinanceIndex().then(res => {
        let {shopMessage} = res.data || {}
        let {id} = shopMessage || {}
        _self.$set(_self.currentItem, 'id', id)
      }).finally(() => _self.boo.loading = false)
    },
    jumpPage(routeName){
      let _self = this
      _self.$router.push({name: routeName})
    },
    reset(){
      this.currentItem = {}
      this.boo.flash = false
      this.$nextTick(() => {
        this.boo.flash = true
      })
    },
    startTimer(){
      let _self = this
      _self.timerObj.timer = setInterval(() => {
        _self.timerObj.seconds--
        if(_self.timerObj.seconds === 0){
          _self.timerObj.seconds = 60
          _self.timerObj.loading = false
          _self.timerObj.tips = '重新获取验证码'
          clearInterval(_self.timerObj.timer)
        }else{
          _self.timerObj.tips = `${_self.timerObj.seconds}s 后重新获取`
        }
      }, 1000)
    },
    async sendCode(){
      let _self = this
      let {accountPhone} = _self.currentItem
      if(!isPhoneNum(accountPhone)) return _self.$message.error('请输入正确格式的手机号')      
      _self.startTimer()
      _self.timerObj.loading = true
      getLpayCode({reg_phone: accountPhone}).then(res => {
        _self.$message.success('验证码已发送');
      }).catch((err) => {
        _self.timerObj.loading = false
        _self.timerObj.seconds = 60
        clearInterval(_self.timerObj.timer)
      })
    },
    radioChange(val){
      let _self = this
      if(val == 1){
        _self.$set(_self.currentItem, 'certificateType', '身份证')
        _self.$set(_self.currentItem, 'certificateNumber', '')
      }else {
        _self.$set(_self.currentItem, 'certificateType', '企业营业执照')
        _self.$set(_self.currentItem, 'certificateNumber', '')
      }
    },
    submit(ref) {
      let _self = this;
          let params = JSON.parse(JSON.stringify(_self.currentItem))
          params['certificateNumber'] = trimAllStr(params['certificateNumber'])
      console.log(params)
      this.$refs[`${ref}-form`].validate( async (valid) => {
        if (valid) {
          _self.boo.isSubmit = true
          let params = JSON.parse(JSON.stringify(_self.currentItem))
          params['certificateNumber'] = trimAllStr(params['certificateNumber'])
          openFinance(params).then(res => {
            _self.$message.success('提交成功')
            _self.$router.replace({name: 'FinanceStore'})
          }).finally(() => {
            _self.boo.isSubmit = false
          })          
        } else {
          return false;
        }
      });
    },
  }
};
</script>
<style scoped lang="scss">
.back-content{
  padding: vh(25) vw(30);
  .back-icon{
    font-size: vh(26);
    cursor: pointer;
  }
  .back-label{
    margin-left: vw(20);
    font-size: 13px;
    color: #3D3D3D;
  }
}
.action-account-container {
  min-height: calc(100vh - 80px);
  .action-account-main{
    align-items: flex-start;
    
    .warning-content{
      flex: 1;
      margin-top: vh(40);
      .warning-label{
        color: #3D3D3D;
        font-size: vh(16);
      }
      .list{
        margin-top: vh(15);
        .item{
          margin-bottom: vh(10);
          align-items: flex-start;
        }
        .item-desc{
          color: #3D3D3D;
          font-size: 13px;
        }
      }
    }
  }
  .sfz-item{
    margin-right: vh(35);
    text-align: center;
    &:last-child{
      margin-right: 0;
    }
    .upload-icon{
      width: vh(240);
      height: vh(125);
    }
    .warning-txt{
      text-align: center;
      font-size: vh(13);
      color: #686868;
      margin-top: vh(20);
    }
  }
  .yyzz-item{
    text-align: center;
    .upload-icon{
      width: vh(240);
      height: vh(120);
    }
    .warning-txt{
      font-size: vh(13);
      color: #686868;
      margin-top: vh(20);
    }
  }
  .app-dialog{
    padding: 0 vw(30);
    width: 60%;
    .form-content-item{
      position: relative;
      .code-btn-unit{
        position: absolute;
        left: vw(400);
        top: 50%;
        transform: translateY(-50%);
        cursor: pointer;
        background: rgba(0, 3, 170, 0.1);
        border-radius: vh(3);
        height: vh(36);
        padding: 0 vw(15);
        .btn-txt{
          font-size: 13px;
          color: #0003AA;
        }
      }
    }
    .form-title{
      margin-top: vh(30);
      margin-bottom: vh(20);
      line-height: vh(34);
      font-size: vh(16);
      color: #0003AA;
    }
    .form-val {
      width: vw(360);
      flex-wrap: nowrap;
      &.no-border{
        border: none;
      }
    }
  }
  .btn-container{
    padding-left: vw(30);
    margin-top: vh(80);
    .btn-item{
      margin-right: vw(30);
      &:last-child{
        margin-right: 0;
      }
      .btn-txt{
        font-size: vh(16);
        width: 260px;
      }
    }
  }
}
</style>